﻿using System;
using System.Reflection;

namespace Snake.Utils
{
    public static class TypeHelper
    {
        /// <summary>
        /// 是否是实体的属性
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static bool IsEntityProperty(this PropertyInfo propertyInfo)
        {
            return propertyInfo.CanRead
                   && propertyInfo.CanWrite
                   && IsSqlSupportedType(propertyInfo.PropertyType)
                   && propertyInfo.GetSetMethod(false) != null;
        }
        /// <summary>
        /// 是否是实体的引用  嵌入类型
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static bool IsEntityReference(this PropertyInfo propertyInfo)
        {
            return propertyInfo.CanRead
                   && propertyInfo.CanWrite
                   && !IsSqlSupportedType(propertyInfo.PropertyType)
                   && propertyInfo.GetSetMethod(false) != null;
        }

        /// <summary>
        /// 判断这个类型是否是SQL支持的类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsSqlSupportedType(Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                return IsSqlSupportedType(Nullable.GetUnderlyingType(type));

            return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime);
        }

        /// <summary>
        /// 判断是否是通用类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="genericType"></param>
        /// <returns></returns>
        public static bool IsGenericType(this Type type, Type genericType)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == genericType;
        }
    }
}
